package eu.codlab.androidemu.origbc;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;

import java.io.File;
import java.io.FileFilter;

import eu.codlab.src.game.R;
import eu.codlab.androidemu.ActivitiesHelper;
import eu.codlab.androidemu.gbcdroid.EmulatorSettings;
import eu.codlab.androidemu.gbcdroid.HelpActivity;
import eu.codlab.androidemu.gbcdroid.ListListener;
import eu.codlab.androidemu.utilities.Game;
import eu.codlab.androidemu.utilities.GameLoader;
import eu.codlab.androidemu.utilities.GameLoaderListener;
import eu.codlab.androidemu.utilities.MoveRomFileManager;
import eu.codlab.game.gameba.activities.GameBoidManager;
import eu.codlab.game.gameba.activities.GamePreferences;

public class MainActivity extends Activity
implements ListListener, FileFilter, FileSelectedListener, GameLoaderListener{
	private static final Uri HELP_URI = Uri.parse(
			"file:///android_asset/faq.html");

	private static final int DIALOG_SHORTCUT = 1;

	private ActivitiesHelper _helper;
	private static Intent emulatorIntent;
	private SharedPreferences settings;
	private boolean creatingShortcut;


	public static final String EXTRA_TITLE = "title";
	public static final String EXTRA_FILTERS = "filters";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR){
			startActivity(new Intent(this, eu.codlab.androidemu.gbcdroid.MainActivity.class));
			this.finish();
		}
		setContentView(R.layout.file_chooser_old);

		settings = getSharedPreferences("MainActivity", MODE_PRIVATE);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		setTitle(R.string.title_select_rom);

		creatingShortcut = getIntent().getAction().equals(
				Intent.ACTION_CREATE_SHORTCUT);

		String path = null;
		if (savedInstanceState != null)
			path = savedInstanceState.getString("currentDir");
		else
			path = getInitialPath();

		_helper = new ActivitiesHelper(this,this, path);

		//set behaviour
		//findViewById(R.id.rom_gripper).setOnClickListener(this);
		findViewById(R.id.goto_sdcard).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				_helper.sdcard();
			}
		});

		findViewById(R.id.goto_parent).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				_helper.parent();
			}
		});

		ListView _l = (ListView)findViewById(R.id.liste);
		View v  = findViewById(R.id.empty);
		if(_l != null && v != null)
			_l.setEmptyView(v);

		String title = getIntent().getStringExtra(EXTRA_TITLE);
		if (title != null)
			setTitle(title);


		//getSupportActionBar().setDisplayHomeAsUpEnabled(false);

		View tmp = findViewById(R.id.this_main);
		_helper.setClickView(tmp);
		tmp = null;



		if(!"6".equals(this.getSharedPreferences("DEBUG", 0).getString("showed_debug", "4"))){
			this.getSharedPreferences("DEBUG", 0).edit().putString("showed", "6").commit();
			DialogInterface.OnClickListener l =
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
					case DialogInterface.BUTTON_NEGATIVE:
						break;
					}
				}
			};

			new AlertDialog.Builder(this).
			setCancelable(false).
			setTitle(R.string.gba_new_help).
			setMessage(R.string.gba_new_help_message).
			setPositiveButton("Ok", l).
			show();
		}
	}

	public void refresh(){
		this.runOnUiThread(new Runnable(){
			public void run(){
				MainActivity.this._helper.changeTo(new File(Environment.getExternalStorageDirectory(), "roms"));
			}
		});
	}
	protected String getInitialPath() {
		return settings.getString("lastGame", null);
	}

	private boolean _is_console = false;
	public boolean isConsole(){
		return _is_console;
	}

	public void onFileSelected(Game type, Uri uri) {
		// remember the last file
		settings = getSharedPreferences("MainActivity", MODE_PRIVATE);

		settings.edit().
		putString("lastGame", uri.getPath()).commit();

		switch(type){
		case GBA:
			GameLoader.loadGBA(this, this, this.findViewById(R.id.large) != null, uri);
			break;
		case GBC:
			GameLoader.loadGBC(this, this, this.findViewById(R.id.large) != null, uri);
			break;
		case UNKNOWN:
		case BIN:
			GameLoader.askBin(this, this, this.findViewById(R.id.large) != null, uri);
			break;
		case ZIP:
			GameLoader.askZip(this, this, this.findViewById(R.id.large) != null, uri);
			break;
		}
	}
	
	public void onFileSelected(Uri uri) {
		// remember the last file
		settings = getSharedPreferences("MainActivity", MODE_PRIVATE);

		settings.edit().
		putString("lastGame", uri.getPath()).commit();

		if(uri.toString().endsWith(".gba")){
			onFileSelected(Game.GBA, uri);
		}else if(uri.toString().endsWith(".zip")){
			onFileSelected(Game.ZIP, uri);
		}else if(uri.toString().endsWith(".bin")){
			onFileSelected(Game.BIN, uri);
		}else{
			onFileSelected(Game.GBC, uri);
		}

	}

	public void onGameLoaderIntent(Intent intent){
		if (!creatingShortcut)
			startActivity(intent);
		else {
			emulatorIntent = intent;
			showDialog(DIALOG_SHORTCUT);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		//getMenuInflater().inflate(R.menu.file_chooser, menu);

		if (!creatingShortcut)
			getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_twitter:
		Intent twitt = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/codlab"));
		startActivity(twitt);
		case R.id.menu_move:
			MoveRomFileManager.promptUser(this);
			return true;
		case R.id.menu_help:
			startActivity(new Intent(this, HelpActivity.class).
					setData(HELP_URI));
			return true;
		case R.id.menu_bluetooth_console:
			if(item != null){
				item.setChecked(!item.isChecked());
			}
			_is_console = item.isChecked();
			break;
		case R.id.menu_settings_gba:
			startActivityForResult(
					new Intent(this, GamePreferences.class), GameBoidManager.REQUEST_SETTINGS);
			return true;

		case R.id.menu_settings:
			startActivity(new Intent(this, EmulatorSettings.class));
			return true;
			/*case R.id.menu_settings_gen:
			startActivity(new Intent(this, eu.codlab.androidemu.gens.EmulatorSettings.class));
			return true;*/
			/*
			 * USELESS in this state
			 * case R.menu.menu_refresh:
			if(adapter != null)
				adapter.refresh();
			return true;

		case R.menu.sdcard:
			if(adapter != null)
				adapter.sdcard();
			break;

		case R.menu.parent:
			if(adapter != null)
				adapter.parent();
			break;*/

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SHORTCUT:
			return createShortcutNameDialog();
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DIALOG_SHORTCUT:
			String name = emulatorIntent.getData().getPath();
			name = new File(name).getName();
			int dot = name.lastIndexOf('.');
			if (dot > 0)
				name = name.substring(0, dot);

			EditText v = ((EditText) dialog.findViewById(R.id.name));
			v.setText(name);
			v.selectAll();
			break;
		}
	}



	private Dialog createShortcutNameDialog() {
		DialogInterface.OnClickListener l =
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				final Dialog d = (Dialog) dialog;
				String name = ((EditText) d.findViewById(R.id.name)).
						getText().toString();

				Intent intent = new Intent();
				intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
						emulatorIntent);
				intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
				Parcelable icon = Intent.ShortcutIconResource.fromContext(
						MainActivity.this, R.drawable.app_icon);
				intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

				setResult(RESULT_OK, intent);
				finish();
			}
		};

		return new AlertDialog.Builder(this).
				setTitle(R.string.shortcut_name).
				setView(getLayoutInflater().inflate(R.layout.shortcut, null)).
				setPositiveButton(android.R.string.ok, l).
				setNegativeButton(android.R.string.cancel, null).
				create();
	}


	public boolean onKey(View v, int keyCode, KeyEvent event) {
		Log.d("onkey",""+keyCode);
		return _helper.onKey(v, keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		if (_helper != null)
			_helper.onSaveInstanceState(outState);
	}

	@Override
	public boolean accept(File pathname) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onListItemClick(String name, View v, int position, long id) {
		_helper.onListItemClick(name, v, position, id);
	}
}
